package wechatmsgmodel

import (
	"bytes"
	"cmdb-go/configmodel"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"time"
)


func WechatTokenGet(corpid, secret string) interface{} {
	GetTokenUrl := fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s",corpid,secret)
	res,_ := http.Get(GetTokenUrl)
	data,_ := ioutil.ReadAll(res.Body)
	resMap := make(map[string]interface{})
	_ = json.Unmarshal(data,&resMap)
	return resMap["access_token"]
}

func WechatMessageSend(username,agentid,contentmessage string )  {
	corpid := configmodel.ConfigGet().WechatCorpid
	secret := configmodel.ConfigGet().WechatSecret
	token := WechatTokenGet(corpid,secret)
	sendMes := map[string]interface{}{
		"touser" : username,
		"msgtype" : "text",
		"agentid" : agentid,
		"text" : map[string]interface{}{
			"content" : contentmessage,
		},
		"enable_id_trans": 0,
		"enable_duplicate_check": 0,
		"duplicate_check_interval": 1800,
	}
	wechatUrl := fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s", token)
	SendMesByte,_ := json.Marshal(sendMes)
	sendMesBody,_ := http.Post(wechatUrl,"application/json", bytes.NewReader(SendMesByte))
	defer sendMesBody.Body.Close()
	fmt.Println(sendMesBody)
}

func AlertMessage(username,containername,containernode string)  {
	agentId := configmodel.ConfigGet().AgentId
	thisTime := fmt.Sprintf("%s",time.Unix(time.Now().Unix(), 0,).Format("2006-01-02 15:04:05"))
	contentMessage := fmt.Sprintf( "<div class='highlight'>容器运行异常</div>" +
		"<div class='highlight'>运行节点: %s</div>" +
		"<div class='highlight'>容器名称: %s</div>" +
		"<div class='highlight'>运行人员: %s</div>" +
		"<div class='highlight'>报警原因: 容器异常</div>" +
		"<div class='highlight'>报警时间: %s</div>",containernode,containername,username,thisTime)
	WechatMessageSend(username,agentId,contentMessage)
}

func RecoverMessage(username,containername,containernode string)  {
	agentId := configmodel.ConfigGet().AgentId
	thisTime := fmt.Sprintf("%s",time.Unix(time.Now().Unix(), 0,).Format("2006-01-02 15:04:05"))
	contentMessage := fmt.Sprintf( "<div class='gray'>容器异常恢复</div>" +
		"<div class='gray'>运行节点: %s</div>" +
		"<div class='gray'>容器名称: %s</div>" +
		"<div class='gray'>运行人员: %s</div>" +
		"<div class='gray'>报警原因: 容器异常</div>" +
		"<div class='gray'>报警时间: %s</div>",containernode,containername,username,thisTime)
	WechatMessageSend(username,agentId,contentMessage)
}

